package org.budo.sentinel.adapter.web.spring;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.spring.web.util.HandlerUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 * @see com.alibaba.csp.sentinel.adapter.servlet.CommonFilter
 * @see com.alibaba.csp.sentinel.slots.block.flow.controller.DefaultController#canPass(Node,int,boolean)
 */
@Slf4j
public class BudoSentinelHandlerInterceptor implements HandlerInterceptor {
    private static final ThreadLocal<Entry> _ENTRY_THREAD_LOCAL = new ThreadLocal<Entry>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String resource = HandlerUtil.getHandlerRequestURI(request, handler);

        Entry entry = null;

        try {
            entry = SphU.entry(resource);
            _ENTRY_THREAD_LOCAL.set(entry);
            return true;
        } catch (BlockException e) {
            log.error("#34 resource=" + resource + "BlockException, e=" + e, e);
            throw e;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Entry entry = _ENTRY_THREAD_LOCAL.get();
        if (null != entry) {
            entry.exit();
        }
    }
}